package com.atguigu.gmall.order.interceptor;


import com.atguigu.gmall.common.utils.CookieUtils;
import com.atguigu.gmall.common.utils.JwtUtils;
import com.atguigu.gmall.order.pojo.UserInfo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.UUID;

/**
 * 拦截器只有一个，就是tomcat里的拦截器，目的在于统一获取登录状态
 * 不能用局部过滤器，因为要做未登录也能加入购物车功能
 * Thread --> ThreadLocalMap --> threadLocal作为key弱引用 载荷作为value（强引用）
 *ThreadLocalMap<THREAD_LOCAL,UserInfo>   key为THREAD_LOCAL，value为泛型UserInfo
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {

    private static final ThreadLocal<UserInfo> THREAD_LOCAL = new ThreadLocal<UserInfo>();

    //执行方法之前先执行前置拦截器
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //System.out.println("这是拦截器的前置方法");
        UserInfo userInfo = new UserInfo();
        String userId = request.getHeader("userId");
        userInfo.setUserId(Long.valueOf(userId));
        THREAD_LOCAL.set(userInfo);
        //目的在于统一获取登录状态，不管有没有登录都放行 return true
        return true;
    }

    /**
     *可以从本地线程的局部变量中获取载荷  ThreadLocalMap<THREAD_LOCAL,UserInfo>
     */
    public static UserInfo getUserInfo(){
      return  THREAD_LOCAL.get();
    }



    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
                                Exception ex) throws Exception {
        // 由于这里使用的是tomcat线程池（线程不会结束），所以必须显式的调用该方法，否则会导致内存泄漏
        THREAD_LOCAL.remove();

    }
}
